package com.gitee.target123.develop.common.bean;

import com.alibaba.fastjson.serializer.ValueFilter;
import com.gitee.target123.develop.common.util.Java8DateFormatUtil;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

/**
 * fastjson toJSONString方法 对象属性类型转换
 */
public class LocalDateTimeValueFilter implements ValueFilter {

    private DateTimeFormatter dateFormatter = null;

    private DateTimeFormatter dateTimeFormatter = null;

    public LocalDateTimeValueFilter() {
    }

    /**
     * @param datePattern if null, default {@code yyyy-MM-dd}
     * @param dateTimePattern if null, default {@code yyyy-MM-dd HH:mm:ss}
     */
    public LocalDateTimeValueFilter(String datePattern, String dateTimePattern) {
        if (datePattern!=null) this.dateFormatter = DateTimeFormatter.ofPattern(datePattern);
        if (dateTimePattern!=null) this.dateTimeFormatter = DateTimeFormatter.ofPattern(dateTimePattern);
    }

    @Override
    public Object process(Object object, String name, Object value) {
        if (value!=null){
            if (value instanceof LocalDateTime){
                if (dateTimeFormatter!=null){
                    return Java8DateFormatUtil.format((LocalDateTime) value, this.dateTimeFormatter);
                }else {
                    return Java8DateFormatUtil.format((LocalDateTime) value);
                }
            }else if (value instanceof LocalDate){
                if (dateFormatter!=null){
                    return Java8DateFormatUtil.format((LocalDate) value, this.dateFormatter);
                }else {
                    return ((LocalDate) value).toString();
                }
            }else if (value instanceof LocalTime){
                // HH:mm:ss
                return ((LocalTime) value).withNano(0).toString();
            }
        }
        return value;
    }
}
